<template>
  <div class="login">
    <!-- 主标题 -->
    <h1 class="title">蜂农定位系统</h1>

    <!-- 登录表单 -->
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h2 class="index">手机号登录</h2>

      <!-- 手机号输入 -->
      <el-form-item prop="phoneNum">
        <el-input v-model="loginForm.phoneNum" type="text" size="large" auto-complete="off" placeholder="手机号">
          <template #prefix>
            <svg-icon icon-class="phone" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>

      <!-- 验证码输入 + 获取按钮 -->
      <el-form-item prop="SmsCode" v-if="captchaEnabled">
        <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
          <el-input v-model="loginForm.SmsCode" size="large" auto-complete="off" placeholder="验证码" style="width: 63%;"
            @keyup.enter="handleLogin">
            <template #prefix>
              <svg-icon icon-class="validCode" class="el-input__icon input-icon" />
            </template>
          </el-input>

          <el-button class="login-code" type="primary" :loading="codeLoading" @click="getMsgCode"
            style="width: 33%; margin-left: 10px;">
            <span v-if="!codeLoading">{{ codeBtnText }}</span>
          </el-button>
        </div>
      </el-form-item>

      <!-- 记住手机号 -->
      <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px;">
        记住手机号
      </el-checkbox>

      <!-- 登录按钮 -->
      <el-form-item style="width: 100%;">
        <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>

        <!-- 链接区域：左-返回账号登录 -->
        <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 15px; width: 100%">
          <router-link class="link-type" :to="'/login'" replace>
            返回账号登录
          </router-link>
          <!-- 右侧留空，或可加注册链接 -->
          <div></div>
        </div>
      </el-form-item>
    </el-form>

    <!-- 底部版权 -->
    <div class="el-login-footer">
      <span>蜂农管理系统</span>
    </div>
  </div>
</template>

<script setup>
import { getPhoneCode } from "@/api/login";
import Cookies from "js-cookie";
import useUserStore from '@/store/modules/user';
import { ElMessage } from 'element-plus';

const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

// 登录表单
const loginForm = ref({
  phoneNum: "19185410370",
  SmsCode: "",
  rememberMe: false,
  code: "",
  uuid: ""
});

// 校验规则
const loginRules = {
  phoneNum: [{ required: true, trigger: "blur", message: "请输入您的手机号" }],
  SmsCode: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const loading = ref(false);
const codeLoading = ref(false);
const captchaEnabled = ref(true); // 验证码开关
const register = ref(true); // 注册开关
const redirect = ref(undefined);

// 倒计时逻辑
const codeBtnText = ref("获取验证码");
let countdown = 60;
let timer = null;

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

// 登录处理
function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      if (loginForm.value.rememberMe) {
        Cookies.set("phoneNum", loginForm.value.phoneNum, { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        Cookies.remove("phoneNum");
        Cookies.remove("rememberMe");
      }

      userStore.login(loginForm.value)
        .then(() => {
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
          router.push({ path: redirect.value || "/", query: otherQueryParams });
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
}

// 获取短信验证码（带倒计时）
function getMsgCode() {
  if (codeLoading.value) return;

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(loginForm.value.phoneNum)) {
    ElMessage.error("请输入正确的手机号");
    return;
  }

  codeLoading.value = true;
  codeBtnText.value = "发送中...";

  getPhoneCode(loginForm.value)
    .then(res => {
      ElMessage.success("验证码已发送");
      console.log(res);
      startCountdown();
    })
    .catch(() => {
      ElMessage.error("验证码发送失败");
    })
    .finally(() => {
      codeLoading.value = false;
    });


}

// 倒计时函数
function startCountdown() {
  countdown = 60;
  codeBtnText.value = `${countdown}s 后重发`;
  timer = setInterval(() => {
    countdown--;
    if (countdown <= 0) {
      clearInterval(timer);
      codeBtnText.value = "获取验证码";
    } else {
      codeBtnText.value = `${countdown}s 后重发`;
    }
  }, 1000);
}

// 读取 Cookie
function getCookie() {
  const phoneNum = Cookies.get("phoneNum");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    phoneNum: phoneNum === undefined ? loginForm.value.phoneNum : phoneNum,
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
    code: "",
    uuid: ""
  };
}

// 初始化
getCookie();
</script>

<style lang="scss" scoped>
.login {
  display: grid;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
  background-position: center;
  padding: 20px;
  box-sizing: border-box;
}

.title {
  margin: 0;
  padding: 20px 0;
  text-align: center;
  color: #130101;
  font-size: 44px;
  font-weight: bold;
}

.index {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #3b3535;
  font-size: 18px;
}

.login-form {
  justify-self: center;
  align-self: center;
  width: 400px;
  border-radius: 6px;
  background: #ffffff;
  padding: 25px 25px 5px 25px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.link-type {
  color: #409eff;
  text-decoration: none;
  margin: 0 3px;
  font-size: 14px;

  &:hover {
    color: #66b1ff;
    text-decoration: underline;
  }
}
</style>